package cn.tedu.spring.service;

import cn.tedu.spring.entity.User;
import cn.tedu.spring.mapper.DeptMapper;
import cn.tedu.spring.mapper.UserMapper;
import cn.tedu.spring.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.beans.Transient;
import java.util.List;

/**
 * Author：程Sir
 * Name： framework
 * Content:
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;
    //展示所有数据
    public List<UserVO> findAll() {
        List<UserVO> users = userMapper.selectAll();
        return  users;
    }

    //登录功能
    public User findUserByUsername(String username) {
        return userMapper.selectOneByUsername(username);
    }

    //插入用户数据
    public String addUser(User user) {
        //在插入数据之前要判断用户名称（电话号码）是否重复
        User user1 = userMapper.selectOneByUsername(user.getUsername());
        if (user1 != null){
            return "注册失败！该用户已存在。";
        }
        int row = userMapper.insertOne(user);
        if (row !=1){
            return "注册过程中发生未知错误，请稍后重试!";
        }
        return "ok";
    }

    @Transactional // 保持事务的一致性！！！
    // 删除用户信息
    public String removeUser(Integer id) {
        //在插入数据之前要判断用户名称是否存在
        User user1 = userMapper.selectOneById(id);
        if (user1 == null){
            return "删除失败！该用户不存在！";
        }
        int row = userMapper.deleteOne(id);
        if (row !=1){
            return "删除过程中发生未知错误，请稍后重试!";
        }
        return "ok";
    }

    // 通过Id查询用户信息
    public User findUserById(Integer id) {
        return userMapper.selectOneById(id);
    }

    // 更新用户数据
    public String chageUser(User user) {
        User user1 = userMapper.selectOneById(user.getId());
        if (user1 == null){
            return "修改失败！更新的用户不存在！";
        }

        int row = userMapper.updateInfo(user);

        if (row !=1){
            return "更新过程中发生未知错误，请稍后重试!";
        }
        return "ok";
    }
}
